<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    @register="registerDrawer"
    :show-ok-btn="false"
    width="70%"
  >
    <!-- :okAuth="'order:flow:wx:m8OrderFlowWxOut:edit'" -->
    <template #centerFooter>
      <a-button type="primary" v-if="record.showKeep && openType == 1" @click="handleSubmit(1)"
        >暂存</a-button
      >
      <a-button type="primary" v-if="openType == 1" @click="handleSubmit(2)">确认</a-button>
      <a-button
        type="primary"
        v-if="openType == 2"
        :disabled="historyIds && historyIndex == 0"
        @click="--historyIndex"
        >上一个</a-button
      >
      <a-button
        type="primary"
        v-if="openType == 2"
        :disabled="historyIds && historyIndex == historyIds.length - 1"
        @click="historyIndex = ++historyIndex"
        >下一个</a-button
      >
    </template>

    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <Tabs v-model:activeKey="activeKey" tabPosition="left">
      <Tabs.TabPane
        v-for="(item, index) in formTabs"
        :key="index"
        :forceRender="true"
        :tab="item.tabName"
      >
        <SingleForm
          v-if="flag"
          :schemas="item.colList"
          :formConfig="formConfig"
          :data="record"
          ref="singleFormArr"
        />
      </Tabs.TabPane>
    </Tabs>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, watch, unref } from 'vue';
  import { Tabs } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';

  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { formSet } from '/@/api/test/testData';
  import { QueslibPlan, queslibPlanForm, queslibPlanSave } from '/@/api/quesLib/plan/queslibPlan';

  import SingleForm from './singleForm.vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('quesLib.plan');
  const { showMessage } = useMessage();
  const record = ref<QueslibPlan>({} as QueslibPlan);
  const historyIndex = ref();
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增方案') : t('编辑方案'),
  }));
  const singleFormArr = ref<any>(null);
  let formTabs = ref<any>([]);
  let formConfig = ref<any>({});

  let flag = ref(false);

  const activeKey = ref<number>(0);
  const openType = ref<number>(1);
  const catchData: QueslibPlan[] = [];
  let historyIds = [];

  watch(
    () => unref(historyIndex),
    () => {
      loadData();
    },
    { immediate: true },
  );

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    flag.value = false;
    activeKey.value = 0;
    openType.value = data.openType;
    setDrawerProps({ loading: true });

    const res11 = await formSet({ viewCode: 'quesLib_plan_form' });

    formTabs.value = res11.layVoucherView.formTabs;
    formConfig.value = res11.layVoucherView.formConfig;

    // await resetFields();
    const res = await queslibPlanForm(data); //需修改
    record.value = (res.queslibPlan || {}) as QueslibPlan; //需修改
    record.value.__t = new Date().getTime();
    flag.value = true;
    setDrawerProps({ loading: false });
    console.log('record', res.queslibPlan.historyIds);
    if (openType.value == 2 && res.queslibPlan.historyIds) {
      historyIndex.value = res.queslibPlan.historyIds.length - 1;
      catchData[historyIndex.value] = res.queslibPlan;
      historyIds = res.queslibPlan.historyIds;
    }
  });

  async function handleSubmit(ope) {
    let obj: any = {};
    let falg = false;
    await singleFormArr.value.forEach((item) => {
      item.validateForm().then((e) => {
        if (!e) {
          falg = true;
        } else {
          obj = { ...obj, ...e };
        }
      });
    });
    setTimeout(async () => {
      if (falg) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      } else {
        try {
          console.log(obj);
          obj.quesId = record.value.quesId;
          obj.ope = ope;
          setDrawerProps({ confirmLoading: true });
          const params: any = {
            isNewRecord: record.value.isNewRecord,
            id: record.value.id,
          };
          //   data.testDataChildList = await getTestDataChildList();
          const res = await queslibPlanSave(params, obj); //需修改
          showMessage(res.message);
          setDrawerProps({ confirmLoading: false });
          setTimeout(closeDrawer);
          emit('success', obj);
        } catch (error: any) {
          // if (error && error.errorFields) {
          //   showMessage('您填写的信息有误，请根据提示修正。');
          // }
          console.log('error', error);
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }
    }, 0);
  }

  async function loadData() {
    if (openType.value == 2) {
      if (catchData[historyIndex.value]) {
        record.value = catchData[historyIndex.value];
        return;
      }
      const res = await queslibPlanForm({ id: historyIds[historyIndex.value] }); //需修改
      catchData[historyIndex.value] = res.queslibPlan;
      record.value = (res.queslibPlan || {}) as QueslibPlan; //需修改
    }
  }
</script>
